------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib
local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_freeze"] or {}
    end)
end

-------------------------------------------------------------------------------------------------------------------------------------------------
local function talk_fn(theNPC,_table)
    if _table and _table.talk then
        theNPC:DoTaskInTime(0.3,function()

            -- theNPC.npc_base_lib:Say(_table.talk)     
            if theNPC.____ask_item ~= "reviver" then
                theNPC.____ask_item = "reviver"
            else
                theNPC.____ask_item = "amulet"
            end

            theNPC.npc_base_lib:Show_Chat_Bubble({
                image = theNPC.____ask_item,
                num = 1,
                height = 4.3
            })


        end)
    end
end

local function Time_Out_Leave(inst)
    local theNPC = inst.entity:GetParent()
    local time = theNPC.npc_base_lib:Get_Time_Out()
    if time then
        inst:DoTaskInTime(time,function()
            inst:Remove()
            theNPC:AddDebuff("npc_event_leave","npc_event_leave")
            theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.time_out)
            print("Warning : npc time out and leave")
        end)
    end
end
local function Thow_Out_Items(theplayer,flag)
    if TUNING.NPC_CONFIG.REWARDS_LESS == true  then
        if flag then    --- 第二次
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "icecream" ,num = math.random(3,8), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "watermelonicle" ,num = math.random(3,8), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "jammypreserves" ,num = math.random(3,8), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "fruitmedley" ,num = math.random(3,8), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "ice" ,num = math.random(3,8), range = 8 ,height = 10})
        else
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "ice" ,num = math.random(5,15), range = 8 ,height = 10})
        end

    else    --------- LESS/MORE

        if flag then    --- 第二次
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "icecream" ,num = math.random(8,15), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "watermelonicle" ,num = math.random(8,15), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "jammypreserves" ,num = math.random(8,15), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "fruitmedley" ,num = math.random(8,15), range = 8 ,height = 10})
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "ice" ,num = math.random(8,15), range = 8 ,height = 10})
        else
            theplayer.components.npc_base_lib:Throw_Out_Items({ name = "ice" ,num = math.random(20,30), range = 8 ,height = 10})
        end
    end

end
local function Freeze_The_Player(theNPC)
    ---- 只冰冻2次，避免BUG或过多操作
    theNPC.__Freeze_The_Player_Task_Num = 1 + (theNPC.__Freeze_The_Player_Task_Num or 0 )
    if theNPC.__Freeze_The_Player_Task_Num > 2 then
        return
    end

    local theplayer = theNPC.__link_player
    theNPC.npc_base_lib:FaceToInst()
    theNPC.npc_base_lib:Action_Chop()
    theNPC:DoTaskInTime(0.5,function()
        if theplayer.components.freezable and not theplayer.components.freezable:IsFrozen() then
            local x,y,z = theplayer.Transform:GetWorldPosition()
            theplayer.components.freezable:Freeze(math.random(20, 30))
            local canthavetags = { "isdead","INLIMBO", "notarget", "noattack", "flight", "invisible", "playerghost" ,"chester","hutch","wall","structure"}
            local musthavetags = {"freezable"}
            local musthaveoneoftags = {"pig","rabbit","animal","smallcreature","epic","monster","insect"}
            local ents = TheSim:FindEntities(x, 0, z, 20, musthavetags, canthavetags, musthaveoneoftags)
            for k, v in pairs(ents) do
                if v.components.freezable and not v.components.freezable:IsFrozen() then
                    if v:HasTag("player") then
                        v.components.freezable:Freeze(math.random(20, 30))
                    else
                        v.components.freezable:Freeze(480)    
                    end
                end
            end

        end
        Thow_Out_Items(theplayer,theNPC.Thow_Out_Items_Flag or false)
        theNPC.Thow_Out_Items_Flag = not theNPC.Thow_Out_Items_Flag
    end)
end

local function ThePlayer_is_being_frozen(theplayer)
    if theplayer.components.freezable and theplayer.components.freezable:IsFrozen() then
        return true
    else
        return false
    end
end

local function Run_Surround_player(theNPC,theplayer)

    if theNPC.__Freeze_The_Player_Task_Num == 2 and theNPC.surround_reverse_flag_temp == nil then
        theNPC.surround_reverse_flag_temp = true
        theNPC.surround_reverse_flag = not theNPC.surround_reverse_flag
    end

    if theNPC.__stack_temp_task_num == nil then

        if theNPC.npc_base_lib:StackCheck(1,10) == false then

            theNPC.npc_base_lib:Run_Surround_Target_In_Range({
                target = theplayer,
                range = 8,
                num = 6,
                reverse_flag =  theNPC.surround_reverse_flag,  --- 第二次反向
            })

        else
            print("info : NPC Stacked ")
            theNPC.__stack_temp_task_num = 0
            theNPC.surround_reverse_flag = not theNPC.surround_reverse_flag   
            theNPC.npc_base_lib:Run_Around_Target_In_Range({clean = true})  

        end

    else --- 发生阻塞,换个行动方案

        theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 6,random_range_flag = true})
        theNPC.npc_base_lib:Run_Surround_Target_In_Range({clean = true})
        theNPC.__stack_temp_task_num = ( theNPC.__stack_temp_task_num or 0) + 1
        if theNPC.__stack_temp_task_num > 20 then
            theNPC.__stack_temp_task_num = nil
        end

    end




    local temp_time = theNPC.components.npc_everything_data:Add("Time666",1)
    if temp_time%20 == 0 or temp_time == 1 then
        theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.hahaha)
    end
end
-------------------------------------------------------------------------------------------------------------------------------------------------
local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    Time_Out_Leave(inst)

    -- theNPC.npc_base_lib:Equip_Random_Hat()
    theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()

    theNPC:AddTag("INLIMBO")
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
    theNPC.npc_event = inst.prefab
    theNPC:AddTag("Unable_To_Refuse")
    theNPC.npc_base_lib:Equip(SpawnPrefab("nightstick"))
    theNPC.npc_base_lib:Equip(SpawnPrefab("icehat"))
    theNPC:HasTag("woodcutter") -- 砍的动作快一些
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
        print("Warning : theNPC.__link_player == nil")
        return
    end

    if theNPC.event_step == nil then

        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 3,fn = Freeze_The_Player}) == true then
            theNPC.event_step = 1
        end        
    elseif theNPC.event_step == 1 then        
        theNPC.event_step = theNPC.event_step + 1
    elseif theNPC.event_step == 2 then
        theNPC.event_step = theNPC.event_step + 1
    elseif theNPC.event_step == 3 then

        Run_Surround_player(theNPC,theplayer)

        if ThePlayer_is_being_frozen(theplayer) == false then
            theNPC.event_step = 4
        end
    elseif theNPC.event_step == 4 then
        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 3,fn = Freeze_The_Player}) == true then
            theNPC.event_step = 5
        end
    elseif theNPC.event_step == 5 then
        theNPC.event_step = theNPC.event_step + 1
    elseif theNPC.event_step == 6 then
        theNPC.event_step = theNPC.event_step + 1
    elseif theNPC.event_step == 7 then

        Run_Surround_player(theNPC,theplayer)

        if ThePlayer_is_being_frozen(theplayer) == false then
            theNPC.event_step = 10
        end
    elseif theNPC.event_step == 10 then

        inst:Remove()
        -- theNPC.npc_base_lib:Say("Bye ~ ")
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.2, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_freeze", fn)
